1.4 Visualizing Dart's Abstract Syntax Tree:An Exploration with AST Viewer

In previous articles 1.3 Fasta:The Abstract Syntax Tree Constructor of Dart SDK, we introduced the Fasta interpreter, and you must be curious about how the Fasta interpreter constructs a syntax tree based on Listeners.

Since the Fasta interpreter is complex, we will proceed step by step. In this section, let's first take a look at what Dart's AST looks like.

What does Dart's Abstract Syntax Tree look like?

While browsing the Dart SDK source code, I stumbled upon an AST Viewer built into the SDK. It's a TUI (Text-based User Interface) command-line application developed using Dart, quite interesting.

It's located at \front_end\tool\parser_direct_ast\viewer.dart.

For the following Dart code:

int add(int a, int b) {
	return a + b;
}

Using the AST Viewer to view it, the screenshot is as follows. First, the root of the syntax tree is a CompilationUnit.

Pasted image 20231108114904.png

This is an interactive program. Press enter to access the child nodes of CompilationUnit:

Pasted image 20231108115012.png

Inside, the CompilationUnit has two elements: MetadataStar and TopLevelDeclaration. Move the blue bar to TopLevelDeclaration and press enter to go inside:

Pasted image 20231108115159.png

Inside, there's a TopLevelMethod. Going further into it:

Pasted image 20231108115254.png

I immediately notice "add", which seems to be our method signature. Enter the BlockFunctionBody:

Pasted image 20231108115354.png

It's a return statement. Going into it:

Pasted image 20231108115428.png

Finally, we arrive at the logic of a + b.

From this progressively unfolding relationship, we can appreciate the "tree" aspect of the abstract syntax tree. Just the syntax tree for a simple a + b is this extensive, imagine how large the tree would be for actual engineering projects with tens of thousands of lines of Dart code!

Another observation is the diversity of syntax tree node types: CompilationUnit, MetadataStar, TopLevelDeclaration, BlockFunctionBody, etc. We will delve into these in the "Dart AST" series later on.

Isn't using AST viewer.dart to view the syntax tree intuitive? It's worth mentioning that its code implementation is also quite interesting. It incorporates an in-built TUI framework, adopts a component-based programming approach, and its programming style is very similar to Flutter's!

Note: This could lead to a future article, "Developing Reactive TUI Applications with Dart".


本文作者:Maeiee

本文链接:1.4 Visualizing Dart's Abstract Syntax Tree:An Exploration with AST Viewer

版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!


喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!